//
//  TimeRecord.swift
//  WaveformDemo
//
//  Created by liyahao on 2025/4/10.
//

import SwiftUI

struct RecordingView: View {
    @StateObject var vModel = AudioRecorder()
    private let waveformHeight: CGFloat = 300
    @Environment(\.dismiss) var dismiss
    
    var body: some View {
        VStack {
            VStack(spacing: 6) {
                Text("新录音")
                    .foregroundColor(.black)
                    .font(.title.weight(.semibold))
                
                if !vModel.placeName.isEmpty {
                    Label(vModel.placeName, systemImage: "location")
                        .foregroundColor(.secondary)
                        .font(.footnote.weight(.semibold))
                }
            }
            .frame(maxWidth: .infinity)
            .overlay(alignment: .trailing) {
                Button {
                    
                } label: {
                    Image(systemName: "ellipsis.circle")
                        .foregroundColor(Color.orange)
                        .font(.title2.weight(.medium))
                    
                }
            }
            .padding([.top, .horizontal])
            
            
            GeometryReader { geometry in
                ZStack {
                    Color.gray.opacity(0.1)
                    ScrollViewReader { proxy in
                        ScrollView(.horizontal, showsIndicators: false) {
                            WaveformView(
                                samples: $vModel.audioSamples,
                                viewWidth: geometry.size.width,
                                sampleRate: vModel.sampleRate
                            )
                        }
                        .onChange(of: vModel.audioSamples.count) { _ in
                            if vModel.isRecording { proxy.scrollTo("canvasContent", anchor: .trailing) }
                        }
                    }
                    TimeIndicator()
                        .frame(height: waveformHeight - 40)
                }
            }
            .frame(height: waveformHeight)
            .padding(.vertical)
            Spacer()
            VStack(spacing: 60) {
                Text("\(Int(vModel.duration).formatTime)")
                    .foregroundColor(.black)
                    .font(.title.weight(.semibold))
                
                PlayCtrlView()
                    .foregroundColor((vModel.isRecording || vModel.audioSamples.isEmpty) ? .gray : .black)
                    .disabled(vModel.isRecording || vModel.audioSamples.isEmpty)
                
                VStack {
                    Button {
                        if vModel.audioSamples.isEmpty, let url = recordPath() {
                            vModel.startRecording(audioFilePath: url)
                        } else {
                            if vModel.isRecording {
                                vModel.pauseRecording()
                            } else {
                                vModel.reStartRecording()
                            }
                        }
                    } label: {
                        ZStack {
                            RoundedRectangle(cornerRadius: 40)
                                .stroke(Color.red.opacity(0.6), style: StrokeStyle(lineWidth: 4))
                                .frame(width: 170, height: 60)
                            
                            if vModel.isRecording {
                                Image(systemName: "pause.fill")
                                    .foregroundColor(Color.red.opacity(0.6))
                                    .font(.system(size: 40, weight: .semibold))
                            } else {
                                Text("继续")
                                    .font(.system(size: 20, weight: .semibold))
                                    .foregroundColor(Color.red.opacity(0.6))
                                    .frame(width: 158, height: 48)
                                    .background(Color.red.opacity(0.2))
                                    .clipShape(RoundedRectangle(cornerRadius: 40))
                            }
                        }
                    }
                }
                .frame(maxWidth: .infinity)
                .overlay(alignment: .trailing) {
                    Button {
                        vModel.stopRecording()
                        self.dismiss()
                    } label: {
                        Text("完成")
                            .font(.system(size: 20, weight: .semibold))
                            .foregroundColor(Color.orange)
                    }
                }
                .padding(.horizontal)
            }
            .padding()
        }
    }
    
    func recordPath() -> URL? {
        if let audio = PathTool.audios {
            // 创建临时文件URL
            let tmp = Date(timeIntervalSinceNow: 0).timeIntervalSince1970
            let name = String(tmp).components(separatedBy: ".")[0] + ".m4a"
            return URL(filePath: audio.appendingPath(name))
        }
        return nil
    }
}

// --- Preview ---
#Preview {
    RecordingView()
}
